// pages/cashbook/index.js
const { API_PREFIX } = require('../../utils/config.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cashbookList: [],
    formDialogVisible: false,
    formValue: '',
    currentCashbook: {},

    slideButtons: [
      {
        text: '修改',
      }
    ],
    buttons: [{ text: '取消' }, { text: '确定' }],
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.handleGetCashbooks()
  },

  /**
   * 获取用户拥有的所有账本
   */
  handleGetCashbooks: function () {
    var userId = wx.getStorageSync('userId')
    if (!userId) return
    
    var that = this
    wx.request({
      url: `${API_PREFIX}/cashbooks`,
      data: { coopUserId: userId },
      success: function (res) {
        if (res.data && res.data.code === '0000') {
          that.setData({ cashbookList: res.data.data })
        }
      }
    })
  },

  /**
   * 新增或修改账本时弹出对话框
   */
  handleShowDialog: function (e) {
    var { id } = e.target.dataset
    if (id) { // 修改
      var { cashbookList } = this.data
      var currentCashbook = cashbookList.find(item => item.id === id)
      this.setData({ currentCashbook, formValue: currentCashbook.name })
    }

    this.setData({ 
      formDialogVisible: true
     })
  },

  /**
   * 点击对话框按钮
   */
  handleClickDialogBtn: function (e) {
    if (e.detail.index === 0) { // 点击取消
      return this.setData({ 
        formDialogVisible: false, 
        formValue: '', 
        currentCashbook: {}, 
      })
    }

    const { formValue, currentCashbook } = this.data
    if (!formValue) {
      return wx.showToast({
        title: '账本不能为空',
      })
    }

    const that = this
    // 发送请求，新增 or 修改账本
    if (currentCashbook.id) {   // 修改
      wx.request({
        url: `${API_PREFIX}/cashbook/${currentCashbook.id}`,
        method: 'PUT',
        data: { name: formValue },
        success: function (res) {
          if (res.data && res.data.code === '0000') {
            that.handleGetCashbooks()
            that.setData({
              formDialogVisible: false,
              formValue: '',
              currentCashbook: {},
            })
          }
        }
      })
    } else { // 新增
      var userId = wx.getStorageSync('userId')
      wx.request({
        url: `${API_PREFIX}/cashbook`,
        method: 'POST',
        data: { name: formValue, userId },
        success: function (res) {
          if (res.data && res.data.code === '0000') {
            that.handleGetCashbooks()
            that.setData({ 
              formDialogVisible: false,
              formValue: '',
              currentCashbook: {}, 
            })
          }
        }
      })
    }
  },

  /**
   * 修改模态框中输入框的值
   */
  handleInputChange: function (e) {
    this.setData({ formValue: e.detail.value })
  },

})